#!/usr/bin/env python
#import ffnet
import numpy
import pylab
import time
import cPickle as pickle
import scipy
import scipy.stats
import os, sys
from pyinotify import WatchManager, Notifier, ProcessEvent, EventsCodes
import re
sys.path.append('.')
import pyximport;pyximport.install()
from utils import LoadFile


def PlotFile(filename,redraw=False):
    if not redraw and len(pylab.get_fignums())==0:
        return 0
    elif not redraw:
        pylab.waitforbuttonpress(1)
        pylab.show()
        return 0
    
    data=LoadFile(filename)
    if len(data)==0:return
    sizes=data[:,1]
    WCTimes=data[:,3]
    IOTimes=data[:,5]
    rusage=data[:,6]
    rates=data[:,8]
    MRUTimes=data[:,7]
    ix=numpy.argsort(sizes)
    Sizes    = numpy.array(sizes)[ix]
    WCTimes  = numpy.array(WCTimes)[ix]
    CPUTimes = numpy.array(rusage)[ix]
    IOwait   = numpy.array(IOTimes)[ix]
    Rates    = numpy.array(rates)[ix]
    MRUTimes   = numpy.array(MRUTimes)[ix]
    psize=3

    fig=pylab.figure(num=4,figsize=(15,8))
    pylab.ion()
    pylab.clf()
    ax1 = pylab.subplot2grid((4,1), (0, 0), rowspan=3)#fig.add_subplot(111)
    ax1.set_title(filename+(" %s"%time.asctime()))
    ax1.set_ylabel('Time[s]')
    ax3 = pylab.subplot2grid((4,1), (3, 0),rowspan=1)
    #pylab.subplots_adjust(left=0.07, right=0.95, top=0.95, bottom=0.06)    
    ax1.minorticks_on()
    ax1.grid(True,which='both')
    ax1.plot(Sizes,WCTimes,color='blue',marker='.',linestyle='None',alpha=0.3,markersize=psize,label='WallClock')
    ax1.plot(Sizes,IOwait,color='green',marker='.',linestyle='None',alpha=0.5,markersize=psize,label='IOwait')
    ax1.plot(Sizes,CPUTimes,color='cyan',marker='.',linestyle='None',alpha=0.4,markersize=psize,label='CPU')
    ax1.plot(Sizes,MRUTimes,color='DarkOrange',marker='.',linestyle='None',alpha=0.15,markersize=psize,label='Machine CPU')
    
    ax1.legend()
    pylab.minorticks_off()    
    ax3.grid(True)
    
    ax3.plot(Sizes,Rates,color='green',marker='.',linestyle='None',alpha=0.5,markersize=psize,label='')
    ax3.set_ylabel('Rate[MB/s]')
    ax3.set_xlabel('Size[MB]')  
    pylab.draw()
    pylab.savefig("Pics/%s.png"%os.path.basename(filename))
    """
    difsizes=sorted(list(set(Sizes)))

    fig=pylab.figure(num=5,figsize=(8,5))
    pylab.ion()
    pylab.clf()
    pylab.grid(True)
    for i in range(len(difsizes)):
	    jj=numpy.where(Sizes==difsizes[i])
	    x=Sizes[jj]
	    #y=WCTimes[jj]
	    y=IOwait[jj]
	    pylab.hist(y,bins=50,alpha=0.1)
    #pylab.xlabel('WCTimes')
    pylab.xlabel('IOwait')
    pylab.draw()"""
    while pylab.waitforbuttonpress(10)!=None:
        pylab.show()
    pylab.show()
    return 1
    

def Monitor(path):
    f=None	
    class PClose(ProcessEvent):
        def process_IN_CLOSE(self, event):
            f = event.name and os.path.join(event.path, event.name) or event.path
            print 'close event: ' + f
            if '.log' in f:PlotFile(f,redraw=True)
            else:return           

    wm = WatchManager()
    notifier = Notifier(wm, PClose())
    wm.add_watch(path, EventsCodes.OP_FLAGS['IN_CLOSE_WRITE'])
    #|EventsCodes.OP_FLAGS['IN_CLOSE_NOWRITE'])

    try:
        while 1:
            notifier.process_events()
            if notifier.check_events(timeout=1000*3):
                notifier.read_events()
            else:
                PlotFile(f,redraw=False)
    except KeyboardInterrupt:
        notifier.stop()
        return


if __name__ == '__main__':
	path        = "data/"
        Monitor(path)
